<template>
  <el-dialog
    title="标题档案查看"
    :visible.sync="dialogVisible"
    :fullscreen="true"
    :before-close="handleClose"
  >
    <div class="wrapper">
      <div class="leftWarp">
        <el-card class="box-card">
          <div
            class="nameStyle"
            :style="{ height: isFullScreen ? '100vh' : heightCard }"
          >
            <p
              v-for="(item, index) in dataName"
              :key="index"
              @click="clickPersonName(item, index)"
              :class="{ highlight: index === personNameIndex }"
            >
              {{ item.personName }}
            </p>
          </div>
        </el-card>
      </div>
      <div class="centerWarp">
        <div
          class="left"
          :style="{ height: isFullScreen ? '100vh' : heightTree }"
        >
          <el-tree
            ref="tree"
            style="margin-left: 10px; margin-top: 5px; margin-bottom: 5px"
            :data="treeData"
            node-key="id"
            :props="defaultProps"
            highlight-current
            @node-click="handleNodeClick"
            :current-node-key="currentNodekey"
            :default-expanded-keys="[currentNodekey]"
          ></el-tree>
        </div>
        <div class="right">
          <div
            class="thumbnail"
            :style="{ height: isFullScreen ? '100vh' : heightY }"
          >
            <template v-if="newImageData && newImageData.length > 0">
              <img
                v-for="(image, index) in newImageData"
                :src="image.description"
                :key="index"
                :style="{
                  width: '140px',
                  height: '200px',
                  border: index === selectedImageIndex ? '2px solid red' : '',
                }"
                @click="selectImage(index)"
              />
            </template>
            <div
              v-else
              style="text-align: center; color: black; margin-top: 20px"
            >
              暂无查看权限
            </div>
          </div>
          <div
            class="bigPicture"
            :style="{ height: isFullScreen ? '100vh' : heightY }"
          >
            <img
              :src="
                selectedImageIndex !== null && newImageData[selectedImageIndex]
                  ? newImageData[selectedImageIndex].description
                  : ''
              "
              alt=""
              style="width: 100%; height: 100%"
            />
          </div>
        </div>
      </div>
      <div class="rightWarp">
        <p style="font-size: 20px; margin-left: 35px">距离查看档案结束:</p>
        <p style="width: 260px;font-size: 20px; margin-left: 5px">{{ applyTime }}</p>
        <button
          v-if="!isFullScreen"
          :class="{ buttonOne: true, active: activeButton == 'fullScreen' }"
          @click="fullScreen"
        >
          全屏
        </button>
        <button
          v-else
          :class="{ buttonOne: true, active: activeButton == 'exitFullScreen' }"
          @click="exitFullScreen"
        >
          退出全屏
        </button>
        <button
          v-if="!pageFlag"
          :class="{ buttonOne: true, active: activeButton == 'bothPage' }"
          @click="bothPage"
        >
          双页
        </button>
        <button
          v-else
          :class="{ buttonOne: true, active: activeButton == 'billPage' }"
          @click="billPage"
        >
          单页
        </button>
        <button
          :class="{ buttonOne: true, active: activeButton == 'highDefinition' }"
          @click="highDefinition"
        >
          高清
        </button>
        <button
          :class="{ buttonOne: true, active: activeButton == 'help' }"
          @click="help"
        >
          帮助
        </button>
        <button
          :class="{ buttonOne: true, active: activeButton == 'upPage' }"
          @click="upPage"
        >
          上一页
        </button>
        <button
          :class="{ buttonOne: true, active: activeButton == 'downPage' }"
          @click="downPage"
        >
          下一页
        </button>
        <button
          v-if="printFlag"
          :class="{ buttonOne: true, active: activeButton == 'print' }"
          @click="print"
        >
          打印
        </button>
      </div>
      <!-- 双页 -->
      <bothPagePop
        v-if="bothPagePopFlag"
        ref="bothPagePopRefs"
        :name="name"
        :idCard="idCard"
      ></bothPagePop>
      <!-- 点击帮助，弹出蒙层页 -->
      <div class="mask">
        <div class="interMask">
          <div class="one">
            <div class="menuList"></div>
            <div
              style="
                border: 1px solid rgb(0, 0, 0);
                height: 30px;
                width: 0px;
                margin-left: 115px;
                margin-top: 30px;
                margin-bottom: -30px;
              "
            ></div>
            <div class="menuListText">切换人员</div>
          </div>
          <div class="two">
            <div class="treeList"></div>
            <div
              style="
                border: 1px solid rgb(0, 0, 0);
                height: 30px;
                width: 0px;
                margin-left: 115px;
                margin-top: 30px;
                margin-bottom: -30px;
              "
            ></div>
            <div class="treeListText">
              【右键】加入<br />
              打印列表
            </div>
          </div>
          <div class="three">
            <div class="thumbnailList"></div>
            <div class="thumbnailListTextTwo" @click="dontHelp">
              点击关闭帮助
            </div>

            <div class="thumbnailListText">
              【悬浮】查看缩略图<br />
              【右键】加入打印列<br />
              表或从打印列表移除
            </div>
          </div>
          <div class="four">
            <div class="buttonList"></div>
            <div class="buttonListText">是否全屏</div>
            <div class="buttonListText1">单双页切换</div>
            <div class="buttonListText3">原始/高清图片切换</div>
            <div class="buttonListText4">帮助</div>
            <div class="buttonListText5">上一页</div>
            <div class="buttonListText6">下一页</div>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>
  
<script>
import store from "@/store";
import {
  getMaterialTree,
  clickMaterial,
  getImgFromCacheByFlag,
  getDetail,
  archiveViewApplyTime,
} from "@/api/datacentersg/achives/documentApi";
import bothPagePop from "@/views/datacentersg/archives/documentArchives/bothPagePop";

import { treeToList, listToTree } from '@/utils'

export default {
  components: { bothPagePop },
  data() {
    return {
      heightY: window.innerHeight - 80 + "px",
      heightTree: window.innerHeight - 80 + "px",
      heightCard: window.innerHeight - 120 + "px",
      imageData: [],
      newImageData: [],
      treeData: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      activeButton: "highDefinition",
      isFullScreen: false,
      pageFlag: false,
      helpFlag: true,
      isHighDefinition: true, // 默认让高清按钮高亮
      selectedImageIndex: 0,
      currentNodekey: "",
      dialogVisible: true,
      dataName: [],
      personNameData: null,
      personNameIndex: 0,
      materialid: "1",
      description: "",
      name: "",
      idCard: "",
      currentPageIndex: 0,
      bothPagePopFlag: false,
      printFlag: false,
      isEmpowerLableAll: false,
      detailEmpowerLables: [],
      applyTime: "",
      timer:null
    };
  },
  created() {
    document.addEventListener("fullscreenchange", this.handleFullscreenChange);
  },
  beforeUnmount() {
    document.removeEventListener("fullscreenchange", this.exitFullScreen);
  },
  methods: {
    init(row) {
      this.dialogVisible = true;
      this.row = row;
      if (this.row.applyType === 2) {
        this.printFlag = true;
      } else {
        this.printFlag = false;
      }
      this.personNameIndex = 0;
      this.archiveApplyTime();
      this.getListDetail();
    },
    // 点击人名
    clickPersonName(personNameItem, index) {
      this.newImageData = [];
      this.personNameData = personNameItem;
      this.name = personNameItem.personName; //用作显示出name和idCard
      this.idCard = personNameItem.idCard;
      this.personNameIndex = index; //设置选中的索引
      if(personNameItem && personNameItem.empowerLables) {
        this.detailEmpowerLables = personNameItem.empowerLables.split(",");
      }
      this.getMaterialTree();
    },

    //详情
    getListDetail() {
      this.newImageData = [];
      const params = {
        userId: store.getters.user_id.toString(),
        token: store.getters.token.toString(),
        data: {
          applyId: this.row.applyId,
        },
      };
      getDetail(params).then((result) => {
        if (result.result) {
          this.dataName = result.resultdata.data.personList;
          this.name = this.dataName[0].personName;
          this.idCard = this.dataName[0].idCard;
          this.isEmpowerLableAll = this.dataName[0].empowerLable === "全部";
          if (this.isEmpowerLableAll) {
            this.detailEmpowerLables = this.dataName[0].empowerLable
          } else {
            let empowerLables = "";
            if (
              this.dataName &&
              this.dataName[0] &&
              this.dataName[0].empowerLable
            ) {
              empowerLables = this.dataName[0].empowerLable;
            }
            this.detailEmpowerLables = empowerLables.split(",");
            console.log(this.detailEmpowerLables,'22222')
          }
          this.getMaterialTree();
        }
      });
    },
    archiveApplyTime() {
      const params = {
        userId: store.getters.user_id.toString(),
        token: store.getters.token.toString(),
        data: {
          applyId: this.row.applyId,
        },
      };
      archiveViewApplyTime(params).then((result) => {
        if (result.result && result.resultdata.data) {
          let remainingTime = result.resultdata.data; // 获取剩余时间字符串，例如 "09:09:07"
          let timeArray = remainingTime.split(":"); // 将时间字符串拆分成时、分、秒
          let hours = parseInt(timeArray[0]);
          let minutes = parseInt(timeArray[1]);
          let seconds = parseInt(timeArray[2]);
          const updateTimer = () => {
            if (hours === 0 && minutes === 0 && seconds === 0) {
              // 倒计时结束，关闭弹框
              this.$emit("countdownFinished");
              this.dialogVisible = false;
            } else {
              // 更新剩余时间并显示在页面上
              this.applyTime = `${hours}小时${minutes}分钟${seconds}秒`;
              if (seconds > 0) {
                seconds--;
              } else {
                if (minutes > 0) {
                  minutes--;
                  seconds = 59;
                } else {
                  hours--;
                  minutes = 59;
                  seconds = 59;
                }
              }
              // 设置下一次更新定时器
            }
          };
          updateTimer()
          this.timer = setInterval(updateTimer, 1000)
          // 第一次调用更新定时器函数
  
        }
      });
    },

    // 小图点击只有展示大图
    selectImage(index) {
      this.selectedImageIndex = index;
    },
    //处理tree数据的方法
    arrangeTreeData(){

      return 
    },
    // tree树数据
    getMaterialTree() {
      const params = {
        name: this.name,
        idCard: this.idCard,
      };
      getMaterialTree(params).then((result) => {
        if (result.data.res_code === "0000") {
          let treeList = result.data.res_data
          // detailEmpowerLables
          // this.treeData = result.data.res_data;

          this.setTreeDataList(treeList)


          if(this.treeData[0].children[0] ) {
            this.handleNodeClick(this.treeData[0].children[0]); // 默认展示第一个目录下的图片
          }else if(this.treeData[0]){
            this.handleNodeClick(this.treeData[0]);
          }

          this.dialogVisible = true;
        } else if (result.data.res_code === "0001") {
          this.treeData = [];
          this.imageData = [];
          this.$message({
            message: result.data.res_msg,
            type: "warning",
          });
        }
      });
    },

    setTreeDataList(trees) {
      if(this.detailEmpowerLables === '全部') {
        this.treeData = trees
        return
      }
      let list = JSON.parse(JSON.stringify(treeToList(trees)))
      list = list.map(e => {
        e.children = null
        return e
      })
      let imgs = this.detailEmpowerLables
      if(!Array.isArray(imgs)) return;
      imgs = imgs.map(e => e.split('_')[0] || '')
      // imgs = [...imgs, '关于其母亲的政审证明']
      let listRes = [...list.filter(f => imgs.includes(f.name))]
      let parents = []
      const findParent = (ls) => {
        let parentIds = ls.map(e => e.parentId)
        let parts = list.filter(f => parentIds.includes(f.id))
        parents = [...parents, ...parts]
        let isAllParent = parts.every(e => e.parentId === 'ZA')
        if(!isAllParent) {
          findParent(parts)
        }
      }
      findParent(listRes)
      console.log("setTreeData", parents, listRes)
      let tlist = [...listRes, ...parents]
      const map = new Map()
      tlist.forEach(e => {
        map.set(e.id, e)
      })
      let arr = tlist.values()
      let treeList = listToTree([...arr])
      this.treeData = treeList
    },

    handleNodeClick(data) {
      if (data.children && data.children.length > 0) {
        // 点击的是父节点，不执行任何操作
        return;
      }
      this.currentNodekey = data.id;
      console.log(this.currentNodekey,"当前点击的目录的id")
      this.nameTree = data.name;
      const materialid = this.materialid && this.currentNodekey;
      const params = {
        name: this.name,
        idCard: this.idCard,
        materialid: materialid, //点击的目录ID
      };
      clickMaterial(params).then((result) => {
        if (result.code === 0) {
          const { res_data } = result.data;
          if (this.isEmpowerLableAll) {
            this.newImageData = res_data;
          } else {
            let infoList = this.detailEmpowerLables;
            // console.log(this.detailEmpowerLables,'22222')
            let list = [];
            if (Array.isArray(res_data)) {
              list = res_data.filter((f) =>
                infoList.includes(data.name + "_" + f.fileName)
              );
            }
            this.newImageData = list;
          }

          this.getImageList(); //调用base64的大图
        }
      });
    },
    getImageList() {
      this.newImageData.forEach((item, i) => {
        const paramsNew = {
          name: this.name,
          idCard: this.idCard,
          fileName: item.fileName, //文件名
        };
        getImgFromCacheByFlag(paramsNew).then((result) => {
          if (result.code === 0) {
            this.$set(item, "description", result.data.res_data);
          }
        });
      });
    },
    // 点击全屏
    fullScreen() {
      this.activeButton = "fullscreen";
      const elem = document.documentElement;
      if (elem.requestFullscreen) {
        elem.requestFullscreen();
      } else if (elem.mozRequestFullScreen) {
        elem.mozRequestFullScreen();
      } else if (elem.webkitRequestFullscreen) {
        elem.webkitRequestFullscreen();
      } else if (elem.msRequestFullscreen) {
        elem.msRequestFullscreen();
      }
      this.isFullScreen = true; // 添加一个变量用于标记是否处于全屏模式
    },
    handleFullscreenChange() {
      this.isFullScreen = document.fullscreenElement !== null;
      if (!this.isFullScreen) {
        this.exitFullScreen();
      }
    },
    // 退出全屏
    exitFullScreen() {
      this.activeButton = "exitFullScreen";
      if (document.exitFullscreen) {
        document.exitFullscreen();
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
      } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen();
      } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
      }
      this.isFullScreen = false; // 修改变量标记退出全屏模式
    },
    // 双页
    bothPage() {
      this.activeButton = "bothPage";
      this.bothPagePopFlag = true;
      this.$nextTick(() => {
        this.$refs.bothPagePopRefs.init(this.newImageData, this.treeData);
      });
      this.pageFlag = true;
    },
    // 单页
    billPage() {
      this.activeButton = "billPage";
      this.bothPagePopFlag = false;
      // this.$nextTick(() => {
      this.$refs.bothPagePopRefs.close();
      // });
      this.pageFlag = false;
    },
    // 帮助
    help() {
      if (this.pageFlag === true) {
        this.activeButton = "help";
        var element = document.querySelector(".mask");
        element.style.display = "none";
      } else if (this.pageFlag === false) {
        this.activeButton = "help";
        var element = document.querySelector(".mask");
        element.style.display = "block";
        this.helpFlag = false;
      }
    },
    dontHelp() {
      var element = document.querySelector(".mask");
      element.style.display = "none";
      this.helpFlag = true;
    },
    // 上一页
    upPage() {
      this.activeButton = "upPage";
      if (this.bothPagePopFlag === false) {
        if (this.currentPageIndex > 0) {
          this.currentPageIndex--;
          this.selectImage(this.currentPageIndex);
        } else {
          this.$message({
            message: "已是最顶层页数",
            type: "warning",
          });
        }
      } else {
        this.$refs.bothPagePopRefs.showPreviousImages();
      }
    },
    // 下一页
    downPage() {
      this.activeButton = "downPage";
      if (this.bothPagePopFlag === false) {
        if (this.currentPageIndex < this.newImageData.length - 1) {
          this.currentPageIndex++;
          this.selectImage(this.currentPageIndex);
        } else {
          this.$message({
            message: "已是最低层页数",
            type: "warning",
          });
        }
      } else {
        this.$refs.bothPagePopRefs.showNextImages();
      }
    },
    print() {
      this.activeButton = "print";
    },
    // 点击高清图片
    highDefinition() {
      this.activeButton = "highDefinition";
      this.isHighDefinition = true;
      this.getMaterialTree();
      this.$message({
        message: "当前浏览的已经是高清图片了",
        type: "success",
      });
    },
    handleClose() {
      clearInterval(this.timer)
      this.applyTime = ''
      this.dialogVisible = false;
    },
  },
};
</script>

  <style scoped>
.wrapper {
  width: 100vw;
  background: #eee;
  height: auto;
}
.leftWarp {
  float: left;
  width: 200px;
}
.nameStyle {
  text-align: center;
  font-size: 18px;
  color: #409eff;
  overflow-y: scroll;
}
.nameStyle p {
  padding: 5px;
  height: 40px;
}
.highlight {
  background-color: #c6e2ff;
  padding: 5px;
  height: 40px;
}
.centerWarp {
  float: left;
}
>>> .el-tree-node__content {
  height: 60px;
}

/deep/ .el-tree > .el-tree-node > .el-tree-node__content {
  font-weight: 900;
  /* color: red; */
  background: #cfe5fc;
}
/deep/
  .el-tree
  > .el-tree-node
  > .el-tree-node__children
  > .el-tree-node
  > .el-tree-node__content
  > .el-tree-node__label {
  font-weight: 700;
}
/deep/.el-tree--highlight-current
  .el-tree-node.is-current
  > .el-tree-node__content {
  background: #6baef1;
}

>>> .el-tree-node__content {
  /* background-color: #CFE5FC; */
  margin-top: 2px;
}
.left {
  float: left;
  margin-left: 3.625vw;
  background: #f7f2ec;
  width: 18.417vw;
  overflow-y: scroll;
}
.right {
  float: left;
  margin-left: 15px;
  background: #f7f2ec;
}
.thumbnail {
  width: 8.813vw;
  overflow-y: scroll;
  float: left;
  margin-bottom: 5px;
  background: #fff;
}
.bigPicture {
  float: left;
  width: 800px;
  margin-bottom: 5px;
  margin-right: 10px;
  background: #fff;
  margin-left: 10px;
}
.rightWarp {
  width: 200px;
  margin-top: 100px;
  float: left;
}
.buttonOne {
  background: #009ae8;
  width: 70px;
  height: 50px;
  font-size: 16px;
  border-radius: 10px;
  border: 1px solid #ccc;
  color: #fff;
  line-height: 50px;
  text-align: center;
  margin-left: 150px;
  margin-top: 8px;
  box-shadow: 2px 2px 10px #ccc;
}
.mask {
  display: none;
  width: 100vw;
  height: 100vh;
  opacity: 0.6;
  background: #6f6f6f;
  z-index: 2000;
  position: absolute;
  top: 0;
}
.one {
  width: 300px;
  height: 100%;
  margin: 3.302vw 0 0px 0.042vw;
  float: left;
}
.menuList {
  background: #fff;
  width: 200px;
  height: 3.042vw;
}
.two {
  width: 18.417vw;
  height: 100%;
  margin: 3.344vw 0 0 -31px;
  float: left;
}
.treeList {
  background: #fff;
  width: 18.417vw;
  height: 1.042vw;
}
.three {
  width: 10.417vw;
  height: 100%;
  margin: 20px 0 0 7px;
  float: left;
}
.thumbnailList {
  background: #fff;
  width: 10.417vw;
  height: 45.042vw;
}
.four {
  width: 5.417vw;
  height: 100%;
  margin: 11.438vw 0 0 48.5vw;
  float: left;
}
.buttonList {
  background: #fff;
  width: 5.417vw;
  height: 23.042vw;
}
.menuListText {
  width: 150px;
  height: 40px;
  color: #fff;
  background: #000;
  text-align: center;
  line-height: 40px;
  margin-top: 30px;
  margin-left: 45px;
  border-radius: 10px;
}
.treeListText {
  width: 150px;
  height: 5.083vw;
  color: #fff;
  background: #000;
  text-align: center;
  line-height: 40px;
  margin-top: 30px;
  margin-left: 45px;
  border-radius: 10px;
}
.thumbnailListTextTwo {
  width: 7.813vw;
  height: 2.083vw;
  color: #fff;
  background: #000;
  text-align: center;
  font-size: 16px;
  line-height: 2.083vw;
  margin-top: -33.437vw;
  margin-left: 15.344vw;
  border-radius: 10px;
}
.thumbnailListText {
  width: 7.813vw;
  height: 6.083vw;
  color: #fff;
  background: #000;
  text-align: center;
  line-height: 2.083vw;
  margin-top: 8.437vw;
  margin-left: 15.344vw;
  border-radius: 10px;
}
.buttonListText {
  width: 150px;
  height: 40px;
  color: #fff;
  background: #000;
  text-align: center;
  line-height: 40px;
  margin-top: -21.2vw;
  margin-left: -9.656vw;
  border-radius: 10px;
}
.buttonListText1 {
  width: 150px;
  height: 40px;
  color: #fff;
  background: #000;
  text-align: center;
  line-height: 40px;
  margin-top: 1.4vw;
  margin-left: -9.656vw;
  border-radius: 10px;
}
.buttonListText2 {
  width: 150px;
  height: 40px;
  color: #fff;
  background: #000;
  text-align: center;
  line-height: 40px;
  margin-top: 0.8vw;
  margin-left: -9.656vw;
  border-radius: 10px;
}
.buttonListText3 {
  width: 150px;
  height: 40px;
  color: #fff;
  background: #000;
  text-align: center;
  line-height: 40px;
  margin-top: 0.8vw;
  margin-left: -9.656vw;
  border-radius: 10px;
}
.buttonListText4 {
  width: 150px;
  height: 40px;
  color: #fff;
  background: #000;
  text-align: center;
  line-height: 40px;
  margin-top: 0.8vw;
  margin-left: -9.656vw;
  border-radius: 10px;
}
.buttonListText5 {
  width: 150px;
  height: 40px;
  color: #fff;
  background: #000;
  text-align: center;
  line-height: 40px;
  margin-top: 0.8vw;
  margin-left: -9.656vw;
  border-radius: 10px;
}
.buttonListText6 {
  width: 150px;
  height: 40px;
  color: #fff;
  background: #000;
  text-align: center;
  line-height: 40px;
  margin-top: 0.8vw;
  margin-left: -9.656vw;
  border-radius: 10px;
}
.active {
  background: #fbae26;
  color: #fff;
  font-size: 16px;
}
</style>